//
//  EJBasePresentationController.m
//  JoyssomEdu
//
//  Created by 刘爽 on 2019/8/21.
//  Copyright © 2019 Joyssom. All rights reserved.
//

#import "EJBasePresentationController.h"

@interface EJBasePresentationController ()<UIViewControllerAnimatedTransitioning>

@property (nonatomic, strong) UIView * bgView;

@property (nonatomic, strong) UIView * presentationWrapperView;


@end

@implementation EJBasePresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController {
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    if (self) {
        presentedViewController.modalPresentationStyle = UIModalPresentationCustom;
        _bgTap = YES;
        _animatedTime = 0.35;
    }
    return self;
}

- (void)presentationTransitionWillBegin {
    self.bgView.alpha = 0;
    [self.containerView addSubview:_bgView];
    
    self.bgView.alpha = 1.f;
}

- (void)presentationTransitionDidEnd:(BOOL)completed {
    if (!completed) {
        self.bgView = nil;
    }
}

- (void)dismissalTransitionWillBegin {
    self.bgView.alpha = 0.f;
}

- (void)dismissalTransitionDidEnd:(BOOL)completed {
    if (completed) {
        [_bgView removeFromSuperview];
        _bgView = nil;
    }
}

- (CGSize)sizeForChildContentContainer:(id<UIContentContainer>)container withParentContainerSize:(CGSize)parentSize {
    if (container == self.presentedViewController) {
        return self.presentedViewController.preferredContentSize;
    } else {
        return [super sizeForChildContentContainer:container withParentContainerSize:parentSize];
    }
}

- (CGRect)frameOfPresentedViewInContainerView {
    
    CGRect containerViewBounds = self.containerView.bounds;
    CGSize presentedViewContentSize = [self sizeForChildContentContainer:self.presentedViewController withParentContainerSize:containerViewBounds.size];
    
    // The presented view extends presentedViewContentSize.height points from
    // the bottom edge of the screen.
    CGRect presentedViewControllerFrame = containerViewBounds;
    presentedViewControllerFrame.size.height = presentedViewContentSize.height;
    if (presentedViewContentSize.width < containerViewBounds.size.width) {
        presentedViewControllerFrame.size.width = presentedViewContentSize.width;
        presentedViewControllerFrame.origin.x = (CGRectGetWidth(containerViewBounds) - presentedViewContentSize.width) / 2;
        presentedViewControllerFrame.origin.y = (CGRectGetHeight(containerViewBounds) - presentedViewContentSize.height) / 2;
    } else {
        presentedViewControllerFrame.origin.y = CGRectGetMaxY(containerViewBounds) - presentedViewContentSize.height;
    }
    return presentedViewControllerFrame;
}

- (void)containerViewWillLayoutSubviews {
    [super containerViewWillLayoutSubviews];
    self.bgView.frame = self.containerView.bounds;
    
    _presentationWrapperView.frame = self.frameOfPresentedViewInContainerView;
}

- (void)preferredContentSizeDidChangeForChildContentContainer:(id<UIContentContainer>)container {
    [super preferredContentSizeDidChangeForChildContentContainer:container];
    if (container == self.presentedViewController) {
        [self.containerView setNeedsLayout];
    }
}

#pragma mark - UIViewControllerTransitioningDelegate
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source {
    return self;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return self;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return [transitionContext isAnimated] ? _animatedTime : 0.f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIView *containerView = transitionContext.containerView;

    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    _presentationWrapperView = toView;
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    
    BOOL isPresenting = (fromViewController == self.presentingViewController);
    
    CGRect fromViewFinalFrame = [transitionContext finalFrameForViewController:fromViewController];
    CGRect toViewInitialFrame = [transitionContext initialFrameForViewController:toViewController];
    CGRect toViewFinalFrame = [transitionContext finalFrameForViewController:toViewController];
    
    [containerView addSubview:toView];
    
    if (isPresenting) {
        if (toViewFinalFrame.size.width < CGRectGetWidth(containerView.bounds)) {
            toView.frame = toViewFinalFrame;
            toView.center = CGPointMake(CGRectGetMidX(containerView.bounds), CGRectGetMidY(containerView.bounds));
            toView.transform = CGAffineTransformMakeScale(0.95, 0.95);
        } else {
            toViewInitialFrame.origin = CGPointMake(CGRectGetMinX(containerView.bounds), CGRectGetMaxY(containerView.bounds));
            toViewInitialFrame.size = toViewFinalFrame.size;
            toView.frame = toViewInitialFrame;
        }
    } else {
        fromViewFinalFrame = CGRectOffset(fromView.frame, 0, CGRectGetHeight(fromView.frame));
    }
    
    NSTimeInterval transitionDuration = [self transitionDuration:transitionContext];
    
    [UIView animateWithDuration:transitionDuration animations:^{
        if (isPresenting) {
            if (toViewFinalFrame.size.width < CGRectGetWidth(containerView.bounds)) {
                toView.transform = CGAffineTransformIdentity;
            } else {
                toView.frame = toViewFinalFrame;
            }
        } else {
            fromView.frame = fromViewFinalFrame;
        }
    } completion:^(BOOL finished) {
        BOOL wasCancelled = [transitionContext transitionWasCancelled];
        [transitionContext completeTransition:!wasCancelled];
    }];
    
}

- (void)animationEnded:(BOOL)transitionCompleted {
    
}

#pragma mark - action
- (void)handleTapBg {
    [self.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - getter or setter
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.frame = self.containerView.bounds;
        _bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];;
        if (_bgTap) {
            UITapGestureRecognizer * tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBg)];
            [_bgView addGestureRecognizer:tapBg];
        }
    }
    return _bgView;
}

@end
